package com.glsc.ngateway.common.xir.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class XirDatasourceConfig {
    public static final String DS_ORACLE_XIR = "datasourceOracleXir";

    @Resource(name = DS_ORACLE_XIR)
    private DataSource datasourceOracleXir;

    @Bean(name = DS_ORACLE_XIR)
    @ConfigurationProperties("spring.datasource.oracle-xir")
    public DataSource datasourceOracleXir() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "entityManagerFactoryOracleXir")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryOracleXir(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean emf = builder
                .dataSource(datasourceOracleXir)
                .packages("com.glsc.ngateway.common.xir.domain") //设置实体类所在位置
                .persistenceUnit("oracleXirPersistenceUnit")
                .build();
        Properties properties = new Properties();
        //方言
        properties.setProperty("hibernate.dialect", "com.glsc.ngateway.oaflow.utils.CustomOracleDialect");//解决oa oracle sequence min_value过小，重载dialect
        //不需要自动创建、更新、验证数据库表结构
        properties.setProperty("hibernate.hbm2ddl.auto", "none");
        properties.setProperty("hibernate.physical_naming_strategy", "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");
        //输出SQL
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.format_sql", "true");
        //懒加载
        properties.setProperty("hibernate.enable_lazy_load_no_trans", "true");
        emf.setJpaProperties(properties);
        return emf;
    }

    @Bean(name = "entityManagerOracleXir")
    public EntityManager entityManagerOracleXir(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryOracleXir(builder).getObject().createEntityManager();
    }

    @Bean(name = "transactionManagerOracleXir")
    public PlatformTransactionManager transactionManagerOracleXir(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryOracleXir(builder).getObject());
    }

}
